package com.wzy.springcloudhystrix.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;


@RestController
@RequestMapping("timeout")
public class Order超时熔断Controller {

    @GetMapping("getOrderById/{id}")
    @HystrixCommand(fallbackMethod = "getOrderByIdFallbackMethod",threadPoolKey = "timeout-getOrderById",
            commandProperties = {
                    //下面两个属性的含义是 隔离策略是线程，超时时间是50毫秒
                    @HystrixProperty(name = "execution.isolation.strategy", value = "THREAD"),
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "50")
            }
    )
    public OrderDto getOrderById(@PathVariable("id") String id) throws InterruptedException {

        OrderDto iphone12_pro_max = new OrderDto("1", 1000, "iphone12 pro max");
        myWait();
        System.out.println("2 getOrderById 当前线程名称：" + Thread.currentThread().getName());
        return iphone12_pro_max;
    }

    public void myWait() throws InterruptedException {
        System.out.println("1 myWait 当前线程名称：" + Thread.currentThread().getName());
        Random random = new Random();
        int i = random.nextInt(100);
        System.out.println("random num is : " + i);
        Thread.sleep(Long.valueOf(i + ""));
    }

    /**
     * 兜底方法，可作为降级方法
     * @param id
     * @return
     */
    public OrderDto getOrderByIdFallbackMethod(String id) {
        System.out.println("e2 getOrderByIdFallbackMethod 当前线程名称：" + Thread.currentThread().getName());
        return new OrderDto("0", 0, "兜底数据");
    }
}
